(ns user.client
		"Client class that interacts with a server making petitions and retreiving 
		 responses"
(:gen-class)
(:use clojure.contrib.duck-streams user.menuClient)
(:import (java.net Socket) (java.io PrintWriter File FileInputStream FileOutputStream)))

(def *port* 3003)

(defn request-connection
		"Asks the server for a database copy which will be stored on a local folder
		dbname -- name for the file containing the duplicated database (from server)"
		[host]
		(def *host* host)
		(let [socket (Socket. *host* *port*)
			temp-file (File/createTempFile "archivo" "temporal")]
			(with-open [input (.getInputStream socket)
				output (PrintWriter. (.getOutputStream socket))
				output-stream  (FileOutputStream. temp-file)]
				(let [buffer (byte-array 1024)]
					(.println output "connection")
					(.flush output)
					(loop [len (.read input buffer)]
						(if (> len 0)
							(do
								(.write output-stream buffer, 0, len)
								(recur (.read input buffer))
							)
						)
					)
				)
				(.println output "ok")
			)
			(.deleteOnExit temp-file)
			(new-menu-client (.getAbsolutePath temp-file) *host* *port*)
		)
)

(defn make-request 
		"Makes different kinds of request based on the parameters.
		 request -- the petition to be fulfilled
		 dbname -- name for the local file(s)"
		[request host]
		(if (= request "connection") (request-connection host)
	)
)

